package com.yuhong.springbootinit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yuhong.springbootinit.model.dto.invitation.InvitationQueryRequest;
import com.yuhong.springbootinit.annotation.AuthCheck;
import com.yuhong.springbootinit.common.BaseResponse;
import com.yuhong.springbootinit.common.DeleteRequest;
import com.yuhong.springbootinit.common.ErrorCode;
import com.yuhong.springbootinit.common.ResultUtils;
import com.yuhong.springbootinit.constant.UserConstant;
import com.yuhong.springbootinit.exception.BusinessException;
import com.yuhong.springbootinit.exception.ThrowUtils;
import com.yuhong.springbootinit.model.dto.invitation.InvitationAddRequest;
import com.yuhong.springbootinit.model.dto.invitation.InvitationEditRequest;
import com.yuhong.springbootinit.model.dto.invitation.InvitationUpdateRequest;
import com.yuhong.springbootinit.model.entity.Invitation;
import com.yuhong.springbootinit.model.entity.User;
import com.yuhong.springbootinit.model.enums.InvitationStatusEnum;
import com.yuhong.springbootinit.model.enums.UserRoleEnum;
import com.yuhong.springbootinit.model.vo.InvitationVO;
import com.yuhong.springbootinit.service.CandidateService;
import com.yuhong.springbootinit.service.CompanyUserService;
import com.yuhong.springbootinit.service.InvitationService;
import com.yuhong.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.yuhong.springbootinit.model.enums.InvitationStatusEnum.PUBLISHED;

@RestController
@RequestMapping("/invitation")
@Slf4j
public class InvitationController {

    @Resource
    private UserService userService;

    @Resource
    private InvitationService invitationService;

    @Resource
    private CompanyUserService companyUserService;

    @Resource
    private CandidateService candidateService;


    /**
     * 创建
     *
     * @param invitationAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInvitation(@RequestBody InvitationAddRequest invitationAddRequest, HttpServletRequest request) {
        if (invitationAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Invitation invitation = new Invitation();
        BeanUtils.copyProperties(invitationAddRequest, invitation);

        invitation.setStatus(PUBLISHED.getCode());
        invitationService.validInvitation(invitation, true);
//        User loginUser = userService.getLoginUser(request);
        // TODO: 2025/3/6 set 公司名和公司id 从公司用户对应表查
//        CompanyUser companyInfoByUserId = companyUserService.getCompanyInfoByUserId(loginUser.getUserAccount());
//        String companyId = companyInfoByUserId.getCompanyId();
//        String companyName = companyInfoByUserId.getCompanyName();
//        invitation.setCompanyId(companyId);
//        invitation.setCompanyName(companyName);
//        invitation.setUserId(loginUser.getUserAccount());

        boolean result = invitationService.save(invitation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newInvitationId = invitation.getId();
        return ResultUtils.success(newInvitationId);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInvitation(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
//        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Invitation oldInvitation = invitationService.getById(id);
        ThrowUtils.throwIf(oldInvitation == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldInvitation.getUserId().equals(deleteRequest.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = invitationService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 修改邀约内容
     *
     * @param invitationUpdateRequest
     * @return
     */
    @PostMapping("/update")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateInvitation(@RequestBody InvitationUpdateRequest invitationUpdateRequest) {
        if (invitationUpdateRequest == null || invitationUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Invitation invitation = new Invitation();
        BeanUtils.copyProperties(invitationUpdateRequest, invitation);

        // 参数校验
        invitationService.validInvitation(invitation, false);
        long id = invitationUpdateRequest.getId();
        // 判断是否存在
        Invitation oldInvitation = invitationService.getById(id);
        ThrowUtils.throwIf(oldInvitation == null, ErrorCode.NOT_FOUND_ERROR);
        invitation.setId(id);
        boolean result = invitationService.updateById(invitation);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<InvitationVO> getInvitationVOById(long id, HttpServletRequest request) throws JsonProcessingException {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Invitation invitation = invitationService.getById(id);
        if (invitation == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(invitationService.getInvitationVO(invitation, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param postQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Invitation>> listInvitationByPage(@RequestBody InvitationQueryRequest postQueryRequest) {
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        Page<Invitation> postPage = invitationService.page(new Page<>(current, size),
                invitationService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<InvitationVO>> listInvitationVOByPage(@RequestBody InvitationQueryRequest postQueryRequest,
                                                           HttpServletRequest request) {
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Invitation> postPage = invitationService.page(new Page<>(current, size),
                invitationService.getQueryWrapper(postQueryRequest));



        return ResultUtils.success(invitationService.getInvitationVOPage(postPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<InvitationVO>> listMyInvitationVOByPage(@RequestBody InvitationQueryRequest postQueryRequest,
                                                             HttpServletRequest request) {
        if (postQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
//        User loginUser = userService.getLoginUser(request);
        postQueryRequest.setUserId(postQueryRequest.getUserId());
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Invitation> postPage = invitationService.page(new Page<>(current, size),
                invitationService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(invitationService.getInvitationVOPage(postPage, request));
    }

    // endregion


    /**
     * 编辑（用户） 接受邀约&hr撤回邀约、通过邀约 流转邀约状态
     *
     * @param invitationEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editInvitation(@RequestBody InvitationEditRequest invitationEditRequest, HttpServletRequest request) {
        if (invitationEditRequest == null || invitationEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Invitation invitation = new Invitation();
        BeanUtils.copyProperties(invitationEditRequest, invitation);
//        List<String> tags = postEditRequest.getTags();
//        if (tags != null) {
//            post.setTags(JSONUtil.toJsonStr(tags));
//        }
        // 参数校验
        invitationService.validInvitation(invitation, false);

        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda().eq(User::getUserAccount, invitationEditRequest.getHrId());
        User loginUser = userService.getOne(qw);

//        User loginUser = userService.getLoginUser(request);
        long id = invitationEditRequest.getId();
        // 判断是否存在
        Invitation oldInvitation = invitationService.getById(id);
        ThrowUtils.throwIf(oldInvitation == null, ErrorCode.NOT_FOUND_ERROR);

        invitation.setStatus(invitation.getStatus());

        boolean result = invitationService.updateById(invitation);

        if(UserRoleEnum.HR.getText().equals(loginUser.getUserRole()) && PUBLISHED.getCode().equals(oldInvitation.getStatus()) && InvitationStatusEnum.ACCEPTED.getCode().equals(invitation.getStatus())){
            //添加候选人
            boolean isSuccess = candidateService.addCandidate(invitation);
            return ResultUtils.success(result && isSuccess);
        }

        return ResultUtils.success(result);
    }


}
